package com.zyf.wjy.controller;

import com.zyf.wjy.common.Result;
import com.zyf.wjy.entity.SalesRecord;
import com.zyf.wjy.service.ProductService;
import com.zyf.wjy.service.SalesRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 销售记录控制器
 */
@Controller
@RequestMapping("/sales")
public class SalesRecordController {
    
    @Autowired
    private SalesRecordService salesRecordService;
    
    @Autowired
    private ProductService productService;
    
    /**
     * 销售记录列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<SalesRecord> records = salesRecordService.findAll();
        model.addAttribute("records", records);
        model.addAttribute("products", productService.findAll());
        return "sales/list";
    }
    
    /**
     * 获取销售详情
     */
    @GetMapping("/detail/{id}")
    @ResponseBody
    public Result<SalesRecord> detail(@PathVariable Long id) {
        SalesRecord record = salesRecordService.findById(id);
        if (record != null) {
            return Result.success(record);
        } else {
            return Result.error("销售记录不存在");
        }
    }
    
    /**
     * 新增/编辑页面
     */
    @GetMapping("/edit")
    public String edit(@RequestParam(required = false) Long id, Model model) {
        if (id != null) {
            SalesRecord record = salesRecordService.findById(id);
            model.addAttribute("record", record);
        }
        model.addAttribute("products", productService.findAll());
        return "sales/edit";
    }
    
    /**
     * 保存销售记录
     */
    @PostMapping("/save")
    @ResponseBody
    public Result<SalesRecord> save(@RequestBody SalesRecord record) {
        try {
            SalesRecord saved = salesRecordService.save(record);
            return Result.success("保存成功", saved);
        } catch (Exception e) {
            return Result.error("保存失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除销售记录
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Result<Void> delete(@PathVariable Long id) {
        try {
            boolean success = salesRecordService.deleteById(id);
            if (success) {
                return Result.success("删除成功", null);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
}

